package com.lq.ecoldchain.ui.moneypocket

import android.arch.lifecycle.MutableLiveData
import com.lq.ecoldchain.base.viewmodel.BaseViewModel
import com.lq.ecoldchain.entity.AccountDetailBean
import com.lq.ecoldchain.entity.AccountInfoBean
import com.lq.ecoldchain.entity.AccountListBean
import com.lq.ecoldchain.internet.BaseObserver
import com.lq.ecoldchain.util.toast

/*
*2019/1/18 0018  20:28
*function by lq
*/
class PocketViewModel : BaseViewModel() {
    val bean by lazy { MutableLiveData<AccountInfoBean>() }
    val refreshing by lazy { MutableLiveData<Boolean>() }
    val list by lazy { ArrayList<AccountDetailBean>() }
    val adapter by lazy { AccountAdapter(list) }
    var page = 1
    val limit = 10

    init {
        moneyPocket()
        accountRecorder()
        adapter.setOnLoadMoreListener{
            page++
            accountRecorder()
        }
    }

    fun refreshData() {
        refreshing.value = true
        accountRecorder()
    }


    private fun accountRecorder() {
        BaseNetCore.ApiServiceImpl.accountRecorder(page, limit).compose(RxTransformer.switchSchedulers()).subscribe(object : BaseObserver<AccountListBean>() {
            override fun onSuccess(t: AccountListBean?) {
                list.clear()
                adapter.loadMoreComplete()
                if (t!=null && !t.list.isNullOrEmpty()){
                    list.addAll(t.list)
                    if(t.list.size<limit){
                        adapter.loadMoreEnd()
                    }
                }
                adapter.notifyDataSetChanged()
                if (refreshing.value == true)
                    toast { "刷新成功" }
                refreshing.value = false
            }

            override fun onFail(code: String) {
                refreshing.value = false
            }
        })
    }

    private fun moneyPocket() {
        BaseNetCore.ApiServiceImpl.accountMoney().compose(RxTransformer.switchSchedulers()).subscribe(object : BaseObserver<AccountInfoBean>() {
            override fun onSuccess(t: AccountInfoBean?) {
                bean.value = t
            }

            override fun onFail(code: String) {

            }
        })
    }


}